﻿///***************************************************************
/// 시  스  템 : Updms.Crd
/// 단위시스템 : CRD
/// 계      층 : Presentation Layer
/// 프로그램명 : Crd2019r
/// 파  일  명 : Crd2019r.aspx.cs
/// 설      명 : 기간별사용분석표
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2011-02-09 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Data;
using SMFramework.Utility;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Crd.Exe;


namespace Updms.Crd
{
	public partial class Crd2019r : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Crd2019r";
		public static readonly string gs_path_info = "/updms/Crd/" + PID + ".aspx";

		Global global = new Global();

		//검색
		protected string kw1 = "";	// 카드
		protected string kw2 = "";	// 시작년월
		protected string kw3 = "";	// 종료년월

		protected string gs_card_nm = "";	//카드명(월간사용분석표 띄울때)

		//메뉴 선택값
		protected string gs_sm = "";	

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
			else
			{
				CallJavaScriptMethodInAjax("setResize();");
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetCardInfo();
			SetYearMonth();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion				

		#region SetInit, SetSearchParameter

		//초기값설정
		private void SetInit()
		{
			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			kw1 = WebControlUtil.GetCheckBoxListValue(cbl_search_card_cd);
			kw2 = ddl_search_from_year.SelectedValue + "-" + ddl_search_from_month.SelectedValue;
			kw3 = ddl_search_to_year.SelectedValue + "-" + ddl_search_to_month.SelectedValue;
			gs_card_nm = StringUtil.DeleteHtmlTag(WebControlUtil.GetCheckBoxListText(cbl_search_card_cd));
		}

		#endregion

		#region 마스터 Method (SetYearMonth, SetCardInfo)

		// 검색조건의 년월설정
		private void SetYearMonth()
		{
			ddl_search_from_year.Items.Clear();
			ddl_search_to_year.Items.Clear();

			// 현재년도 기준으로 ±2년 -> SEARCH_Y_MIN년부터 현재+1년
			int li_f_year = Convert.ToInt32(SEARCH_Y_MIN);
			int li_t_year = Convert.ToInt32(DateUtil.GetYearEx(1, "yyyy"));
			for (int i = li_f_year; i <= li_t_year; i++)
			{
				string ls_year = i.ToString();
				ddl_search_from_year.Items.Add(new ListItem(ls_year, ls_year));
				ddl_search_to_year.Items.Add(new ListItem(ls_year, ls_year));
			}

			SetYearMonth(-12);
		}

		// 검색조건의 년월설정 - 기간지정
		private void SetYearMonth(int li_term)
		{
			ddl_search_from_year.SelectedValue = DateUtil.GetMonthEx(li_term, "yyyy"); //x개월전년도
			ddl_search_from_month.SelectedValue = DateUtil.GetMonthEx(li_term, "MM"); //x개월전월
			ddl_search_to_year.SelectedValue = DateUtil.GetYearEx(0, "yyyy"); // 현재년도
			ddl_search_to_month.SelectedValue = DateUtil.GetMonthEx(0, "MM"); // 현재월
		}

		//카드정보
		private void SetCardInfo()
		{
			DataSet lo_ds = new DataSet();
			Crd1010m_NT _Crd1010m_NT = new Crd1010m_NT();

			lo_ds.Merge(_Crd1010m_NT.GetCardInfoList("A"));

			cbl_search_card_cd.Items.Clear();
			cbl_search_card_cd.DataSource = lo_ds;
			cbl_search_card_cd.DataMember = "UPDMS_CRD_INFO";
			cbl_search_card_cd.DataTextField = "Card_Nm_Color";
			cbl_search_card_cd.DataValueField = "Card_Cd";
			cbl_search_card_cd.DataBind();

			WebControlUtil.SelectCheckBoxList(cbl_search_card_cd, true);
		}

		#endregion

		#region 디테일 Method (SetChartByAccount)

		//계정별 라인챠트
		private void SetChartByAccount(GridView gv, int row_idx)
		{
			//시리즈
			chart_line.Data.Series = 1;
			string series = String.Empty;

			series = ConversionUtil.ExtractStrBtwnChar(gv.Rows[row_idx].Cells[1].Text, ";\">", "</a>");

			chart_line.Series[0].Text = series;

			//초기화
			chart_line.Data.Clear();

			string monthList = DateUtil.GetDiffMonthList(kw2, kw3);
			string[] monthLists = monthList.Split(',');

			double ld_avg = 0.0; //평균
			int li_sum = 0; //합계
			int li_cnt = 0; //금액이 0이상인 월의 수

			for (int i = 0; i < monthLists.Length; i++)
			{
				int value = Convert.ToInt32(ConversionUtil.RemoveComma(ConversionUtil.ExtractStrBtwnChar(gv.Rows[row_idx].Cells[i + 2].Text, ");\">", "</span>")));
				li_sum = li_sum + value;

				//수동으로 데이터 바인딩
				chart_line.Data[0, i] = value;

				//X축 라벨링
				chart_line.AxisX.Labels[i] = monthLists[i].ToString();

				//0이상일때만 보여준다.
				if (chart_line.Data[0, i] > 0)
				{
					chart_line.Points[0, i].PointLabels.Visible = true;
					li_cnt++;
				}
				else
				{
					chart_line.Points[0, i].PointLabels.Visible = false;
				}
			}

			if (li_cnt > 0)
			{
				ld_avg = li_sum / li_cnt;
			}

			//CustomGridLine 초기화
			chart_line.AxisY.CustomGridLines.Clear();

			//CustomGridLine
			ChartFX.WebForms.CustomGridLine cgl1 = new ChartFX.WebForms.CustomGridLine();
			cgl1.Value = ld_avg;
			cgl1.Color = System.Drawing.Color.Red;
			cgl1.Width = 2;
			cgl1.Text = "Avg. : " + ld_avg.ToString("#,###.##");
			cgl1.Alignment = StringAlignment.Far;
			cgl1.LineAlignment = StringAlignment.Near;
			cgl1.TextColor = Color.Black;

			chart_line.AxisY.CustomGridLines.Add(cgl1);

			mpe_chart_line.Show();
		}

		#endregion

		#region 리스트 (SelectRegionalUsingAnalysisList, SearchProcess)

		//조회 - 합계치
		private void SelectRegionalUsingAnalysisList()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			
			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_dt_from", typeof(string), kw2);
			lo_dp.AddProperty("ls_dt_to", typeof(string), kw3);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
			lo_dp.AddProperty("ls_is_excel", typeof(string), "false");

			using (Crd2019r_NT _Crd2019r_NT = new Crd2019r_NT())
			{
				lo_ds.Merge(_Crd2019r_NT.GetRegionalUsingAnalysisList(lo_dp));
			}

			gv_data_nodata.Visible = !DataSetUtil.CheckRowCount(lo_ds, "UPDMS_CRD_REPORT");
			
			gv_account.DataSource = lo_ds;
			gv_data.DataSource = lo_ds;
			gv_total.DataSource = lo_ds;
			
			gv_account.DataBind();
			gv_data.DataBind();
			gv_total.DataBind();
		}			

		//검색
		private void SearchProcess()
		{
			if (WebControlUtil.IsCheckedItems(cbl_search_card_cd))
			{
				SetSearchParameter();
				h_card_cd.Value = kw1;
				h_card_nm.Value = gs_card_nm;
				SelectRegionalUsingAnalysisList();
			}
			else
			{
				CallMsgBoxInAjax("MSG_ERR_023");	//하나이상의 카드를 선택하세요
			}
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		//ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//계정
		protected void gv_account_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				e.Row.Cells[0].Text
					= "<a href=\"#\" onclick=\"viewChartByAccount('" + e.Row.RowIndex.ToString() + "');\">" + e.Row.Cells[0].Text + "</a>";

				//하단 총계
				if (gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString() == "BB006")
				{
					e.Row.Attributes.Add("class", "total_v3");
					for (int i = 0; i < e.Row.Cells.Count; i++)
					{
						e.Row.Cells[i].Attributes.Add("class", "div_line_tb_dbl");
					}
				}
			}
		}

		//데이터
		protected void gv_data_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			e.Row.Cells[0].Visible = false;	//View_Order 숨기기
			e.Row.Cells[1].Visible = false;	//계정 숨기기
			e.Row.Cells[e.Row.Cells.Count - 1].Visible = false;	//총액 숨기기

			if (e.Row.RowType == DataControlRowType.Header)
			{
				e.Row.HorizontalAlign = HorizontalAlign.Center;

				for (int i = 2; i < e.Row.Cells.Count - 1; i++)
				{
					string ym = e.Row.Cells[i].Text;
					string header = "<span class=\"b hand\" onclick=\"viewMonthlyAmountByCardNAccount('" + ym + "');\">" + ym + "</span>";
					e.Row.Cells[i].Text = Context.Server.HtmlDecode(header);
				}
			}
			
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				//금액컬럼 정렬 및 HtmlDecode
				for (int i = 2; i < e.Row.Cells.Count - 1; i++)
				{
					e.Row.Cells[i].Text = Context.Server.HtmlDecode(e.Row.Cells[i].Text);
					e.Row.Cells[i].HorizontalAlign = HorizontalAlign.Right;
				}
				
				//하단 총계
				if (gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString() == "BB006")
				{
					e.Row.Attributes.Add("class", "total_v3");
					for (int i = 0; i < e.Row.Cells.Count - 1; i++)
					{
						e.Row.Cells[i].Attributes.Add("class", "div_line_tb_dbl");
					}
				}
			}
		}

		//총액
		protected void gv_total_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				//하단 총계
				if (gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString() == "BB006")
				{
					e.Row.Attributes.Add("class", "total_v3");
					for (int i = 0; i < e.Row.Cells.Count; i++)
					{
						e.Row.Cells[i].Attributes.Add("class", "div_line_tb_dbl");
					}
				}
			}
		}

		#endregion

		#region 버튼이벤트

		//6개월
		protected void sbtn_6_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-5);
			SearchProcess();
		}

		//12개월
		protected void sbtn_12_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-12);
			SearchProcess();
		}

		//전체
		protected void sbtn_all_m_Click(object sender, EventArgs e)
		{
			ddl_search_from_year.SelectedIndex = 0;
			ddl_search_from_month.SelectedIndex = 0;
			ddl_search_to_year.SelectedIndex = ddl_search_to_year.Items.Count - 1;
			ddl_search_to_month.SelectedIndex = ddl_search_to_month.Items.Count - 1;

			SearchProcess();
		}

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_dt_from", typeof(string), kw2);
			lo_dp.AddProperty("ls_dt_to", typeof(string), kw3);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
			lo_dp.AddProperty("ls_is_excel", typeof(string), "true");

			using (Crd2019r_NT _Crd2019r_NT = new Crd2019r_NT())
			{
				lo_ds.Merge(_Crd2019r_NT.GetRegionalUsingAnalysisList(lo_dp));
			}

			//2013-01,2013-02... -> 2013-01^2013-01:2013-02^2013-02
			//컬럼수만큼의 크기를 갖는 배열을 생성
			string[] columns = DateUtil.GetDiffMonthList(kw2, kw3).Split(',');
			string[] headerTexts = new string[columns.Length + 2]; // +2(Account_Nm, Total)

			headerTexts[0] = "Account_Nm^" + global.GetLabelNmBySeq(55, LANG_SET);//계정

			for (int i = 1; i < headerTexts.Length - 1; i++)
			{
				headerTexts[i] = columns[i - 1] + "^" + columns[i - 1];
			}

			headerTexts[headerTexts.Length - 1] = "Total^Total";

			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, headerTexts);
		}

		//챠트 생성
		protected void lbtn_set_chart_Click(object sender, EventArgs e)
		{
			SetSearchParameter();
			SetChartByAccount(gv_data, Convert.ToInt32(h_row_idx.Value));
		}

		#endregion

	}
}
